package bg.tu.varna.pms.client.controller;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JList;

import bg.tu.varna.pms.client.ApplicationContext;
import bg.tu.varna.pms.client.gui.ContactListPanel;
import bg.tu.varna.pms.client.listener.ContactlistListener;
import bg.tu.varna.pms.client.model.ContactlistModel;
import bg.tu.varna.pms.model.Contact;
import bg.tu.varna.pms.model.communication.FriendshipMessage.Type;
import bg.tu.varna.pms.model.communication.SyncMessage.OperationType;

public class ContactlistController extends MouseAdapter implements
		ContactlistListener, ActionListener {

	private final ContactListPanel panel;

	public ContactlistController(ContactListPanel panel) {
		this.panel = panel;

		initPanel();

		//mockModel();
	}

	private void mockModel() {
		Contact[] contacts = new Contact[10];
		for (int i = 0; i < 10; i++) {
			Contact c = new Contact();
			c.setNickname("nickname" + i);
			contacts[i] = c;
		}

		ContactlistModel model = new ContactlistModel(contacts);
		panel.setListModel(model);

	}

	private void initPanel() {
		ApplicationContext.getApplicationContext().getUserContext()
				.getContacts();

		panel.addController(this, this);

		setFrameTitle();
		setUserStatus();
		setUserStatusMessage();
	}

	private void setUserStatusMessage() {
		panel.setStatusMessage(ApplicationContext.getApplicationContext()
				.getUserContext().getStatusMessage());
	}

	// TODO
	private void setUserStatus() {
		// panel.setStatus(ApplicationContext.getApplicationContext().getUserContext().getStatus().name());
	}

	private void setFrameTitle() {
		panel.setFrameTitle(ApplicationContext.getApplicationContext()
				.getUserContext().getNickname());
	}

	@Override
	public void contactsModification(Contact[] contacts) {
		panel.setListModel(new ContactlistModel(contacts));
	}

	@Override
	public void contactModification(Contact contact, OperationType type) {
		// TODO Auto-generated method stub

	}

	@Override
	public void contactModification(Contact contact, String message, Type type) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mouseClicked(MouseEvent e) {
		if (e.getClickCount() == 2) {
			JList<String> list = (JList<String>) e.getSource();
			String userName = list.getSelectedValue();
			ApplicationContext.getApplicationContext().getUserContext()
					.crateChatRoom(new String[] {userName});
			
		//	MessagingController.mockChat();
			
		}
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		// Enter key is pressed in user status text field
		ApplicationContext.getApplicationContext().getUserContext()
				.setStatusMessage(panel.getStatusMessage());
	}

}
